package com.example.springboot.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.HomestayNews;
import com.example.springboot.entity.Homestays;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.HomestayNewsMapper;
import com.example.springboot.service.IHomestayNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 民宿资讯表 API控制器 - 不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/api/homestayNews")
public class HomestayNewsApi {
    @Resource
    private IHomestayNewsService iHomestayNewsService;

    @Resource
    private HomestayNewsMapper homestayNewsMapper;

    //获取民宿资讯信息，首页的那四个
    @GetMapping("/list")
    public Result list(){
      List<HomestayNews> homestayNewsList=  iHomestayNewsService.list();
        if (homestayNewsList.isEmpty()) {
            return Result.success(Collections.emptyList()); // 返回空列表
        }

        Collections.shuffle(homestayNewsList); // 打乱顺序
        int endIndex = Math.min(homestayNewsList.size(), 4); // 最多取 6 个
        List<HomestayNews> randomArticles = homestayNewsList.subList(0, endIndex);
        return Result.success(randomArticles);
    }


    //民宿资讯分页返回
    @GetMapping("/page")
    public Result findPage(
                           @RequestParam Integer page,
                           @RequestParam Integer pageSize) {
        QueryWrapper<HomestayNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(iHomestayNewsService.page(new Page<>(page, pageSize), queryWrapper));
    }


    //获取民宿资讯详情
    @GetMapping("/detail/{id}")
    public Result selectDetails(@PathVariable Integer id) {
        // 1. 查询民宿资讯
        HomestayNews article = iHomestayNewsService.getById(id);

        // 2. 返回单条数据
        return Result.success(article);
    }


    //更新阅读量
    @PostMapping("/view/{id}")
    public Result updateViewCount(@PathVariable Integer id) {
        // 1. 查询民宿资讯
        homestayNewsMapper.updateViewCount(id);
        return Result.success();
    }

}
